package algorithm.loadbalance;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class RamdomWeightStragy {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            String ip = radomWeight();
            System.out.println("获取到的IP:"+ip);
        }

    }

    /**
     *  随机权重策略  获取权重总和，每个节点的权重值，从小到右，相当于一个横坐标，随机值位于哪个区间
     *  1 2 2 5 5 7 7
     * @return
     */
    public static String radomWeight(){
        final Map<String,Integer> serverMap = ServerInfo.serverMap;
        // 总节点数
        int totalNodeSize = serverMap.size();
        // 总权重值
        Collection<Integer> values = serverMap.values();
        int total = 0;
        for (Integer weight:values   ) {
            total = total+weight;
        }

        Random random = new Random();
        // 客户端发起一个请求，生成一个随机数，判断这个随机值位于哪个范围
        int randomNum = random.nextInt(total);
        // 与已有的比
        int destWeightSum = 0;
        for (Map.Entry<String, Integer> item : serverMap.entrySet()) {
            Integer weight = item.getValue();
            String ip = item.getKey();
            destWeightSum = destWeightSum + weight;
//            System.out.println(">>"+randomNum+"--"+destWeightSum);
            if(randomNum <= destWeightSum){
                return ip;
            }

        }
        return "";
    }


}
